import type {AxiosResponse} from "axios";
import {VCairnCommand} from "v-cairn";
import type { ResponseData } from './types.ts';
import {ErrorCodes} from "./errorCodes.ts";
import { VCairnEvent } from 'v-cairn';

export class BaseCommand extends VCairnCommand {

    protected errorInSuccess(response: AxiosResponse): boolean {
        // 业务数据中code不为000000都认为失败
        const responseData = response.data as ResponseData;
        return responseData.code !== '000000';
    }

    override serverError(error: any) {
        this.onFail(error.response as AxiosResponse);
    }

    // 子类可以覆盖默认行为
    protected onFailDefaultHandle(response: AxiosResponse) {
        const responseData = response.data as ResponseData;
        console.log(responseData.message);
    }

    protected onFail(response: AxiosResponse) {
        const code = response.data.code as keyof typeof ErrorCodes;
        const codeHandleItem = ErrorCodes[code];
        if (codeHandleItem) {
            if (codeHandleItem.handler) {
                codeHandleItem.handler(codeHandleItem, response);
            } else {
                new VCairnEvent(code, [codeHandleItem, response.data]).emit();
            }
        } else {
            this.onFailDefaultHandle(response);
        }
    }

}